var express = require('express');
var router = express.Router();
const { formidable } = require('formidable')
const { AccountModel, UserModel } = require('../../model/index.js')
const jwt = require('jsonwebtoken')
const authApiCheckMiddleware = require('../../middleware/apiAuth.js')
// const mongoose = require('mongoose')
// const AccountSchema = mongoose.Schema({
//   username: String,
//   dec: String
// })
// const AccountModel = mongoose.model('account', AccountSchema)
// const UserSchema = mongoose.Schema({
//   username: String,
//   password: String
// })
// const UserModel = mongoose.model('users', UserSchema)
// const low = require('lowdb')
// const FileSync = require('lowdb/adapters/FileSync')
// const adapter = new FileSync('data/db.json')
// const db = low(adapter)
// const shortid = require('shortid');
 
/* 上传页面 */
router.post('/portrait', function(req, res, next) {
  const form = formidable({ 
    uploadDir: __dirname + '/../public/images', 
    keepExtensions: true,
    filename: (filename, suffix) => {
      return filename + suffix
    }
  });

  form.parse(req, (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    res.json({ fields, files });
  });
});
/* 注册 */
router.post('/register', async function(req, res, next) {
  const { username, password } = req.body
  if(username && password) {
    UserModel.create(req.body)
    res.render('transferPage', { status: '注册成功', backUrl: '/login' })
  } else {
    res.render('transferPage', { status: '注册失败', backUrl: '/register' })
  }
});
/* 登录 */
router.post('/login', async function(req, res, next) {
  const { username, password } = req.body
  const token = jwt.sign({
    username
  }, 'xig', {
    expiresIn: 60*60*24*7*1000
  })
  console.log(token, 'tokentoken')
  const userInfo = await UserModel.findOne(req.body)
  if(token && userInfo) {
    req.session.username = username
    req.session.password = password
    res.render('transferPage', { status: '登录成功', backUrl: '/account' })
  } else {
    res.render('transferPage', { status: '登录失败', backUrl: '/login' })
  }
});
/* 列表 */
router.get('/account', authApiCheckMiddleware, async function(req, res, next) {
  const accountQuery = await AccountModel.find()
  if(accountQuery) {
    res.json({
      code: 200,
      msg: 'success',
      data: accountQuery
    })
  }
});
/* 退出登录 */
router.post('/loginOut', async function(req, res, next) {
  console.log(req.session, 'ssss')
  req.session.destroy((err) => {
    if(err) return
    res.render('transferPage', { status: '退出登录', backUrl: '/login' })
  })
});
/* 创建列表 */
router.post('/account/create', async function(req, res, next) {
  // const id = shortid.generate()
  // db.get('account').unshift({ id, ...req.body }).write()
  
  const response = await AccountModel.create({ ...req.body })
  if(!response) return res.status = 500  
  res.render('transferPage', { status: '创建成功', backUrl: '/account' })
});


module.exports = router;
